Skip to content

Method: static {...}

1: /**
2: * Copyright (C) 2022 Czech Technical University in Prague
3: *
4: * This program is free software: you can redistribute it and/or modify it under
5: * the terms of the GNU General Public License as published by the Free Software
6: * Foundation, either version 3 of the License, or (at your option) any
7: * later version.
8: *
9: * This program is distributed in the hope that it will be useful, but WITHOUT
10: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12: * details. You should have received a copy of the GNU General Public License
13: * along with this program. If not, see <http://www.gnu.org/licenses/>.
14: */
15: package cz.cvut.kbss.jsonld.serialization.traversal;
16:
17: import cz.cvut.kbss.jsonld.common.BeanAnnotationProcessor;
18: import cz.cvut.kbss.jsonld.common.BeanClassProcessor;
19: import cz.cvut.kbss.jsonld.exception.BeanProcessingException;
20: import cz.cvut.kbss.jsonld.exception.MissingTypeInfoException;
21:
22: import java.lang.reflect.Field;
23: import java.util.Collection;
24: import java.util.Optional;
25: import java.util.Set;
26:
27: /**
28: * Determines the set of types an instance possesses.
29: */
30: class InstanceTypeResolver {
31:
32: /**
33: * Resolves all the types the instance belongs to.
34: * <p>
35: * This includes:
36: * <ul>
37: * <li>{@link cz.cvut.kbss.jopa.model.annotations.OWLClass} values declared on the argument's class
38: * and any of its ancestors.</li>
39: * <li>Value of types field in the instance.</li>
40: * </ul>
41: *
42: * @param instance The instance whose types should be resolved
43: * @return Set of types of the instance
44: */
45: Set<String> resolveTypes(Object instance) {
46: assert instance != null;
47: final Set<String> declaredTypes = BeanAnnotationProcessor.getOwlClasses(instance);
48: final Optional<Field> typesField = BeanAnnotationProcessor.getTypesField(instance.getClass());
49: typesField.ifPresent(f -> {
50: if (!Collection.class.isAssignableFrom(f.getType())) {
51: throw new BeanProcessingException("@Types field in object " + instance + " must be a collection.");
52: }
53: final Collection<?> runtimeTypes = (Collection<?>) BeanClassProcessor.getFieldValue(f, instance);
54: if (runtimeTypes != null) {
55: runtimeTypes.forEach(t -> declaredTypes.add(t.toString()));
56: }
57: });
58: if (declaredTypes.isEmpty()) {
59: throw new MissingTypeInfoException("No type info found on instance " + instance +
60: ". Either annotate the class with @OWLClass or provide a non-empty @Types field. " +
61: "If it is a literal, make sure that the property referencing is not an @OWLObjectProperty");
62: }
63: return declaredTypes;
64: }
65: }